//
//  ViewController.m
//  ASR_Demo
//
//  Created by marco on 16/3/9.
//  Copyright © 2016年 Marco. All rights reserved.
//

#import "ViewController.h"
#import "AQQueue.h"
#import "Player.h"
#import "Recorder.h"
#import "ASRManager.h"
#import "NetworkTools.h"
#import "SVProgressHUD.h"
#import "KeyworkMatchManager.h"
#import "WordModel.h"

@interface ViewController () <UITextViewDelegate>

@property(nonatomic,strong) AQQueue *voiceDataQueue;
@property(nonatomic,strong) Player *player;
@property (nonatomic,strong) Recorder *recorder;

@property (nonatomic,assign) BOOL isStartRecord;
@property (weak, nonatomic) IBOutlet UIButton *btnRecorder;

@property (nonatomic,strong) NSMutableArray *voiceResult;
@property (nonatomic,strong) NSMutableArray *voiceTranslateResult;
@property (weak, nonatomic) IBOutlet UITextView *txtRecorderResult;
@property (weak, nonatomic) IBOutlet UITextView *txtTranslatedResult;
@property (nonatomic,assign) BOOL isTxtRecorderResultDragging;
@property (nonatomic,assign) BOOL isTxtTranslatedResultDragging;

@property (nonatomic,strong) NSMutableArray<NSURLSessionDataTask *> *httpTaskArray;

@property (nonatomic,assign) TranslateType translateType;
@property (nonatomic,assign) SampleRateType sampleRateType;

@property (weak, nonatomic) IBOutlet UISegmentedControl *segSampleRate;

@property (nonatomic,assign) NSInteger logRecorderIdx;
@property (nonatomic,assign) NSInteger logTranslateIdx;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.voiceDataQueue = [[AQQueue alloc] init];
    
    self.player = [[Player alloc] init];
    self.player.voiceDataQueue = self.voiceDataQueue;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(voiceDataComplete:) name:g_kRecorderProcessAudioBuffer object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(asrZHComplete:) name:g_kASRComplete_ZH object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(asrUYGHURComplete:) name:g_kASRComplete_UYGHUR object:nil];
    
    
    _txtRecorderResult.delegate = self;
    _txtTranslatedResult.delegate = self;

    [KeyworkMatchManager sharedManager];
    
    _isStartRecord = NO;
    _voiceResult = [NSMutableArray new];
    _voiceTranslateResult = [NSMutableArray new];
    
    _httpTaskArray = [NSMutableArray new];
    
    _isTxtRecorderResultDragging = NO;
    _isTxtTranslatedResultDragging = NO;
 
    [self setupUyToZh];
    [self setupSampleRate16kb];
    
    _segSampleRate.selectedSegmentIndex = 1;
    _logRecorderIdx = -1;
    _logTranslateIdx = -1;
    
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (IBAction)clickInSide:(id)sender
{
    
    if( _isStartRecord )
    {
        _isStartRecord = NO;
        [_btnRecorder setTitle:NSLocalizedString(@"开始录音", nil) forState:UIControlStateNormal];
        
        [[ASRManager sharedManager] closeSystem];
        
        [self.recorder stop];

        if( ASR_TYPE == kASR_TYPE_KEDAXUNFEI )
        {
            [self.recorder start];
        }
    }
    else
    {
        _isStartRecord = YES;
        
        [_btnRecorder setTitle:NSLocalizedString(@"结束录音", nil) forState:UIControlStateNormal];
        
        ASRSystemType asrSystemType =  kASRSystemType_ZH;
        if( _translateType == kTranslateType_UY_TO_ZH )
        {
            asrSystemType = kASRSystemType_UYGHUR;
        }
        NSString* asrSampleRateType = g_kASRSampleRateRate_8kb;
        if( _sampleRateType == kSamplingRate_16KB)
        {
            asrSampleRateType = g_kASRSampleRateRate_16kb;
        }

        [[ASRManager sharedManager] openSystem:asrSystemType samplingRate:asrSampleRateType];
        
        if( ASR_TYPE == kASR_TYPE_JIEGONGHUASHENG )
        {
            [self.recorder start];
        }

        
    }
}

- (void)setupUyToZh
{
    _translateType = kTranslateType_UY_TO_ZH;
}
- (void) setupZhToUy
{
    _translateType = kTranslateType_ZH_TO_UY;
}
- (void) setupSampleRate8kb
{
    _sampleRateType = kSamplingRate_8KB;
    
    self.recorder = [[Recorder alloc] initWithSampleRate:kRECORDER_8kb];
    self.recorder.voiceDataQueue = self.voiceDataQueue;
}
- (void) setupSampleRate16kb
{
    _sampleRateType = kSamplingRate_16KB;
    
    self.recorder = [[Recorder alloc] initWithSampleRate:kRECORDER_16KB];
    self.recorder.voiceDataQueue = self.voiceDataQueue;
}

#pragma mark event
- (void) voiceDataComplete:(NSNotification *)pNotification
{
    NSData* data = pNotification.object;
    
    if( _translateType == kTranslateType_ZH_TO_UY )
    {
        [[ASRManager sharedManager] realtimeRecog:data type:kASRSystemType_ZH];
    }
    else if( _translateType == kTranslateType_UY_TO_ZH )
    {
        [[ASRManager sharedManager] realtimeRecog:data type:kASRSystemType_UYGHUR];
    }
    
}
//中文识别结束的通知
- (void) asrZHComplete:(NSNotification *)pNotification
{

    [self asrComplete:pNotification.object
     translateMainUrl:TRANSLATE_ZH_TO_UY
     translateType:kTranslateType_ZH_TO_UY];
    
}
//维语识别后的通知
- (void) asrUYGHURComplete:(NSNotification*)pNotification
{
    [self asrComplete:pNotification.object
     translateMainUrl:TRANSLATE_UY_TO_ZH
     translateType:kTranslateType_UY_TO_ZH];

}
-(void)asrComplete:(NSString*)pResult
  translateMainUrl:(NSString*)pMainUrl
     translateType:(TranslateType)pType
{
    
    if( pResult.length <= 0 )
    {
        return;
    }
    
    WordModel* model = [WordModel new];
    model.text = pResult;
    if( pType == kTranslateType_UY_TO_ZH )
    {
        model.keywordRange = [[KeyworkMatchManager sharedManager] matchKeywordRangeForUY:pResult];
    }
    else if( pType == kTranslateType_ZH_TO_UY )
    {
        model.keywordRange = [[KeyworkMatchManager sharedManager] matchKeywordRangeForZH:pResult];
    }
    model.isKeyword = (model.keywordRange.location == NSNotFound) ? NO : YES;
    [_voiceResult addObject:model];
    
    dispatch_async(dispatch_get_main_queue(), ^{

        [self setupRecorderVoiceLabel];
    });
    
    if( SHOW_WORD_TYPE == kSHOW_KEYWORD )
    {
        if( !model.isKeyword )
        {
            return;
        }
    }
 
    NSString* url = [NSString stringWithFormat:@"%@%@",pMainUrl,[pResult stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLSessionDataTask *task = [NetworkTools GET:url params:nil success:^(id json) {
        
        NSString* tgt_text = [json[@"tgt_text"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];//去掉首位换行符
        WordModel* model = [WordModel new];
        model.text = tgt_text;
        if( pType == kTranslateType_ZH_TO_UY )
        {
            model.keywordRange = [[KeyworkMatchManager sharedManager] matchKeywordRangeForUY:tgt_text];
        }
        else if( pType == kTranslateType_UY_TO_ZH )
        {
            model.keywordRange = [[KeyworkMatchManager sharedManager] matchKeywordRangeForZH:tgt_text];
        }
        model.isKeyword = (model.keywordRange.location == NSNotFound) ? NO : YES;
        [_voiceTranslateResult addObject:model];
        [_httpTaskArray removeObject:task];
        
        [self setupTranslateVoiceLabel];
        
    } failure:^(NSError *error) {
        
        [_httpTaskArray removeObject:task];
    }];
    [_httpTaskArray addObject:task];
    
}
- (WordModel*) getWordModel:(NSString*)pResult translateType:(TranslateType)pType
{
    WordModel* model = [WordModel new];
    model.text = pResult;
    if( pType == kTranslateType_UY_TO_ZH )
    {
        model.keywordRange = [[KeyworkMatchManager sharedManager] matchKeywordRangeForUY:pResult];
    }
    else if( pType == kTranslateType_ZH_TO_UY )
    {
        model.keywordRange = [[KeyworkMatchManager sharedManager] matchKeywordRangeForZH:pResult];
    }
    model.isKeyword = (model.keywordRange.location == NSNotFound) ? NO : YES;
    return model;
}
//清除按钮事件
- (IBAction)onCleanClick:(id)sender
{
    if( _isStartRecord )
    {
        [SVProgressHUD showInfoWithStatus:@"请先停止录音" maskType:SVProgressHUDMaskTypeBlack];
        return;
    }

    [self clean];
}
//汉译英 英译汉 段落选择器事件
- (IBAction)translateModelChange:(UISegmentedControl *)sender
{
    if( _isStartRecord )
    {
        [SVProgressHUD showInfoWithStatus:@"请先停止录音" maskType:SVProgressHUDMaskTypeBlack];
        sender.selectedSegmentIndex = sender.selectedSegmentIndex == 1 ? 0 : 1;
        return;
    }
    
    if( 1 == sender.selectedSegmentIndex )
    {
        [self setupZhToUy];
    }
    else if( 0 == sender.selectedSegmentIndex )
    {
        [self setupUyToZh];
    }
    [self clean];
}
- (IBAction)sampleRateModelChange:(UISegmentedControl *)sender
{
    if( _isStartRecord )
    {
        [SVProgressHUD showInfoWithStatus:@"请先停止录音" maskType:SVProgressHUDMaskTypeBlack];
        sender.selectedSegmentIndex = sender.selectedSegmentIndex == 1 ? 0 : 1;
        return;
    }
    
    if( 1 == sender.selectedSegmentIndex )
    {
        [self setupSampleRate16kb];
    }
    else if( 0 == sender.selectedSegmentIndex )
    {
        [self setupSampleRate8kb];
    }
    [self clean];
}

-(void) clean
{
    self.txtRecorderResult.attributedText = nil;
    self.txtTranslatedResult.attributedText = nil;
    [_voiceResult removeAllObjects];
    [_voiceTranslateResult removeAllObjects];
    
    [self.voiceDataQueue clear];
    
    //终止网络请求
    [_httpTaskArray makeObjectsPerformSelector:@selector(cancel)];
    [_httpTaskArray removeAllObjects];
    
    _logRecorderIdx = -1;
    _logTranslateIdx = -1;
}

-(void) setupRecorderVoiceLabel
{
    _txtRecorderResult.attributedText = [self caculateAttributedString:_voiceResult isRecorder:YES];
    if( _translateType == kTranslateType_ZH_TO_UY )
    {
        _txtRecorderResult.textAlignment = NSTextAlignmentLeft;
    }
    else
    {
        _txtRecorderResult.textAlignment = NSTextAlignmentRight;
    }
}
-(void) setupTranslateVoiceLabel
{
    _txtTranslatedResult.attributedText = [self caculateAttributedString:_voiceTranslateResult isRecorder:NO];
    if( _translateType == kTranslateType_ZH_TO_UY )
    {
        _txtTranslatedResult.textAlignment = NSTextAlignmentRight;
    }
    else
    {
        _txtTranslatedResult.textAlignment = NSTextAlignmentLeft;
    }
}
-(NSMutableAttributedString*) caculateAttributedString:(NSArray*)pVoiceResult isRecorder:(BOOL)pIsRecorder
{
    NSMutableString* text = [NSMutableString new];
    for (WordModel* model in pVoiceResult)
    {
        [text appendFormat:@"%@\n",model.text];
    }
    
    NSMutableAttributedString* attrText = [[NSMutableAttributedString alloc] initWithString:text];
    
    NSInteger totalLenth = 0;
    for (NSInteger i = 0; i < pVoiceResult.count; i++)
    {
        WordModel* model = pVoiceResult[i];
        
        if( model.isKeyword )
        {
            NSUInteger location = (totalLenth == 0 ? 0 : totalLenth ) + model.keywordRange.location;
            NSUInteger length = model.keywordRange.length ;
            NSRange range = NSMakeRange(location,length);
            [attrText addAttribute:NSForegroundColorAttributeName
                             value:[UIColor redColor]
                             range:range];
        }
        
        NSRange range = NSMakeRange(totalLenth, model.text.length);
        
        [attrText addAttribute:NSFontAttributeName
                         value:[UIFont systemFontOfSize:18]
                         range:range];
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 10;// 字体的行间距
        [attrText addAttribute:NSParagraphStyleAttributeName
                         value:paragraphStyle
                         range:range];
        
        totalLenth += (model.text.length + 1); //后面有个空格，所以+1

        if( pIsRecorder )
        {
            if( _logRecorderIdx < i )
            {
                KEYWORD_LOG("录音识别：%s\n",[model.text UTF8String]);
                _logRecorderIdx = i;
            }
        }
        else
        {
            if( _logTranslateIdx < i )
            {
                KEYWORD_LOG("关键字翻译：%s\n",[model.text UTF8String]);
                _logTranslateIdx = i;
            }
        }
    }
    return attrText;
}

#pragma mark UIScrollViewDelegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if( scrollView == _txtTranslatedResult )
    {
        _isTxtTranslatedResultDragging = YES;
    }
    else
    {
        _isTxtRecorderResultDragging = YES;
    }
}

-(void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if( scrollView == _txtTranslatedResult )
    {
        _isTxtTranslatedResultDragging = NO;
    }
    else
    {
        _isTxtRecorderResultDragging = NO;
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"%@",NSStringFromCGSize(scrollView.contentSize));
}
#pragma mark UITextViewDelegate
- (void)textViewDidChangeSelection:(UITextView *)textView
{
    if( textView == _txtRecorderResult )
    {
        if( _isTxtRecorderResultDragging )
        {
            return;
        }
    }
    else if( textView == _txtTranslatedResult )
    {
        if( _isTxtTranslatedResultDragging )
        {
            return;
        }
    }

    //获取文本高度
    CGFloat contentSizeHeight = 0.0f;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9) {
        
        CGRect textFrame=[[textView layoutManager]usedRectForTextContainer:[textView textContainer]];
        contentSizeHeight = textFrame.size.height;
        
    }else {
        
        contentSizeHeight = textView.contentSize.height;
    }
    
    CGFloat boundsHeight = textView.bounds.size.height;
    if( contentSizeHeight >= boundsHeight )
    {
        [textView setContentOffset:CGPointMake(0, contentSizeHeight - boundsHeight) animated:YES];
    }
}

@end
